package com.xiong.xtools.citychoose;

import android.app.DatePickerDialog;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xiong.xtools.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Author : 熊文强
 * Time : 2017/9/18
 * Content : 省市县三级联动选择（需要添加MyApplication到清单文件）
 */
public class CityChooseActivity extends AppCompatActivity {
	List<ProvinceInfoModel> provinceList = new ArrayList<>();//全部数据
	protected ArrayList<String> mProvinceDatas;//省
	protected Map<String, ArrayList<String>> mCitisDatasMap = new HashMap<String, ArrayList<String>>();//市
	protected Map<String, ArrayList<String>> mDistrictDatasMap = new HashMap<String, ArrayList<String>>();//区

	protected String mCurrentProviceName;
	protected String mCurrentCityName;
	protected String mCurrentDistrictName;

	protected boolean isDataLoaded = false;
	private View contentView; //选择地区的弹框布局
	private PopupWindow addrPopWindow;
	private WheelView mProvincePicker;
	private WheelView mCityPicker;
	private WheelView mCountyPicker;
	private LinearLayout boxBtnCancel; //取消
	private LinearLayout boxBtnOk;//确定

	private LinearLayout rootview;
	private RelativeLayout mPlaceLayout;//选择地区
	private TextView mPlaceTextView;//填地址

	private MyOnClickListener clickListener;

	private SQLiteDatabase database;
	private String ProvinceId;//省id
	private String CityId;//市id
	private String AreaId;//区id

	private RelativeLayout mBirthdayLayout;//修改生日
	private TextView mDateTextView;//生日

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_city_choose);
		init();
	}

	private void init() {
		findView();
	}

	private void findView() {
		// 地区需要
		rootview = (LinearLayout) findViewById(R.id.info_layout);
		mPlaceLayout = (RelativeLayout) findViewById(R.id.place_layout);
		mPlaceTextView = (TextView) findViewById(R.id.place_textView);
		//生日需要
		mBirthdayLayout = (RelativeLayout) findViewById(R.id.birth_layout);
		mDateTextView = (TextView) findViewById(R.id.date_textView);

		clickListener = new MyOnClickListener();
		mBirthdayLayout.setOnClickListener(clickListener);  // 生日监听
		mPlaceLayout.setOnClickListener(clickListener);     // 地区监听

		database = DBManager.getDBManager(CityChooseActivity.this).getDatabase();
		initProviceSelectView();//设置选地区的弹框
	}

	/**
	 * 各种点击的监听
	 */
	public class MyOnClickListener implements View.OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.birth_layout: // 选择生日
					new DatePickerDialog(CityChooseActivity.this, new DatePickerDialog.OnDateSetListener() {
						@Override
						public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
							mDateTextView.setText(String.format("%d/%d/%d", year, monthOfYear + 1, dayOfMonth));
						}
					}, 1995, 1, 2).show();
					break;
				case R.id.place_layout://选择地区
					if (isDataLoaded) {
						addrPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);
					}
					break;

			}
		}
	}

	/**
	 * 处理选择地区
	 */
	private void initProviceSelectView() {
		contentView = LayoutInflater.from(this).inflate(R.layout.city_addr_picker, null);
		mProvincePicker = (WheelView) contentView.findViewById(R.id.province);
		mCityPicker = (WheelView) contentView.findViewById(R.id.city);
		mCountyPicker = (WheelView) contentView.findViewById(R.id.county);
		boxBtnCancel = (LinearLayout) contentView.findViewById(R.id.box_btn_cancel);
		boxBtnOk = (LinearLayout) contentView.findViewById(R.id.box_btn_ok);

		addrPopWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		addrPopWindow.setFocusable(true);
		addrPopWindow.setOutsideTouchable(false);//设置允许在外点击消失

		mProvincePicker.setOnSelectListener(new WheelView.OnSelectListener() {
			@Override
			public void endSelect(int id, String text) {
				String provinceText = mProvinceDatas.get(id);
				if (!mCurrentProviceName.equals(provinceText)) {
					mCurrentProviceName = provinceText;
					ArrayList<String> mCityData = mCitisDatasMap.get(mCurrentProviceName);
					mCityPicker.resetData(mCityData);
					mCityPicker.setDefault(0);
					mCurrentCityName = mCityData.get(0);

					ArrayList<String> mDistrictData = mDistrictDatasMap.get(mCurrentCityName);
					mCountyPicker.resetData(mDistrictData);
					mCountyPicker.setDefault(0);
					mCurrentDistrictName = mDistrictData.get(0);
				}
			}

			@Override
			public void selecting(int id, String text) {
			}
		});

		mCityPicker.setOnSelectListener(new WheelView.OnSelectListener() {
			@Override
			public void endSelect(int id, String text) {
				ArrayList<String> mCityData = mCitisDatasMap.get(mCurrentProviceName);
				String cityText = mCityData.get(id);
				if (!mCurrentCityName.equals(cityText)) {
					mCurrentCityName = cityText;
					ArrayList<String> mCountyData = mDistrictDatasMap.get(mCurrentCityName);
					mCountyPicker.resetData(mCountyData);
					mCountyPicker.setDefault(0);
					mCurrentDistrictName = mCountyData.get(0);
				}
			}

			@Override
			public void selecting(int id, String text) {

			}
		});

		mCountyPicker.setOnSelectListener(new WheelView.OnSelectListener() {
			@Override
			public void endSelect(int id, String text) {
				ArrayList<String> mDistrictData = mDistrictDatasMap.get(mCurrentCityName);
				String districtText = mDistrictData.get(id);
				if (!mCurrentDistrictName.equals(districtText)) {
					mCurrentDistrictName = districtText;
				}
			}

			@Override
			public void selecting(int id, String text) {

			}
		});

		boxBtnCancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				addrPopWindow.dismiss();
			}
		});

		boxBtnOk.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String addr = mCurrentProviceName + "-" + mCurrentCityName;
				if (!mCurrentDistrictName.equals("其他")) {
					addr += "-" + mCurrentDistrictName;
				}
				Cursor cursor;
				cursor = database.query(TABLE_NAME.TABLE_PROVINCE, new String[]{"provinceid"}, "province = ?", new String[]{mCurrentProviceName}, null, null, null);
				if (cursor.moveToNext()) {
					ProvinceId = cursor.getString(cursor.getColumnIndex("provinceid"));
				}
				cursor = database.query(TABLE_NAME.TABLE_CITY, new String[]{"cityid"}, "city = ?", new String[]{mCurrentCityName}, null, null, null);
				if (cursor.moveToNext()) {
					CityId = cursor.getString(cursor.getColumnIndex("cityid"));
				}
				cursor = database.query(TABLE_NAME.TABLE_AREA, new String[]{"areaid"}, "area = ?", new String[]{mCurrentDistrictName}, null, null, null);
				if (cursor.moveToNext()) {
					AreaId = cursor.getString(cursor.getColumnIndex("areaid"));
				}
				mPlaceTextView.setText(addr);
				addrPopWindow.dismiss();
			}
		});

		// 启动线程读取数据
		new Thread() {

			@Override
			public void run() {
				// 读取数据
				isDataLoaded = readAddrData();

				// 通知界面线程
				new Handler(Looper.getMainLooper()).post(new Runnable() {
					@Override
					public void run() {
						mProvincePicker.setData(mProvinceDatas);
						mProvincePicker.setDefault(0);
						mCurrentProviceName = mProvinceDatas.get(0);

						ArrayList<String> mCityData = mCitisDatasMap.get(mCurrentProviceName);
						mCityPicker.setData(mCityData);
						mCityPicker.setDefault(0);
						mCurrentCityName = mCityData.get(0);

						ArrayList<String> mDistrictData = mDistrictDatasMap.get(mCurrentCityName);
						mCountyPicker.setData(mDistrictData);
						mCountyPicker.setDefault(0);
						mCurrentDistrictName = mDistrictData.get(0);
					}
				});
			}
		}.start();

	}

	/**
	 * 读取地址数据，请使用线程进行调用
	 *
	 * @return
	 */
	protected boolean readAddrData() {
		List<ProvinceInfoModel> provinceList = null;
		try {
			provinceList = takeData(database);//从数据库读出数据
			if (provinceList != null && !provinceList.isEmpty()) {
				mCurrentProviceName = provinceList.get(0).getName();
				List<CityInfoModel> cityList = provinceList.get(0).getCityList();
				if (cityList != null && !cityList.isEmpty()) {
					mCurrentCityName = cityList.get(0).getName();
					List<DistrictInfoModel> districtList = cityList.get(0).getDistrictList();
					mCurrentDistrictName = districtList.get(0).getName();
				}
			}
			mProvinceDatas = new ArrayList<String>();
			for (int i = 0; i < provinceList.size(); i++) {
				mProvinceDatas.add(provinceList.get(i).getName());
				List<CityInfoModel> cityList = provinceList.get(i).getCityList();
				ArrayList<String> cityNames = new ArrayList<String>();
				for (int j = 0; j < cityList.size(); j++) {
					cityNames.add(cityList.get(j).getName());
					List<DistrictInfoModel> districtList = cityList.get(j).getDistrictList();
					ArrayList<String> distrinctNameArray = new ArrayList<String>();
					for (int k = 0; k < districtList.size(); k++) {
						DistrictInfoModel districtModel = new DistrictInfoModel(districtList.get(k).getName());
						distrinctNameArray.add(districtModel.getName());
					}
					mDistrictDatasMap.put(cityNames.get(j), distrinctNameArray);
				}
				mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
			}
			return true;
		} catch (Throwable e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 从数据库读出省市区数据
	 *
	 * @param sqliteDB
	 * @return
	 */
	public List<ProvinceInfoModel> takeData(SQLiteDatabase sqliteDB) {
		ProvinceInfoModel provinceModel;
		CityInfoModel cityMode;
		DistrictInfoModel districtModel;
		List<CityInfoModel> cityList;
		List<DistrictInfoModel> districtList;
		try {
			Cursor cursor = sqliteDB.query(TABLE_NAME.TABLE_PROVINCE, new String[]{"province", "provinceid"}, null, null, null, null, null);
			while (cursor.moveToNext()) {
				provinceModel = new ProvinceInfoModel();
				String province = cursor.getString(cursor.getColumnIndex("province"));
				String provinceid = cursor.getString(cursor.getColumnIndex("provinceid"));
				Cursor cursor1 = sqliteDB.query(TABLE_NAME.TABLE_CITY, new String[]{"city", "cityid"}, "father = ?", new String[]{provinceid}, null, null, null);
				cityList = new ArrayList<>();
				while (cursor1.moveToNext()) {
					cityMode = new CityInfoModel();
					String city = cursor1.getString(cursor1.getColumnIndex("city"));
					String cityid = cursor1.getString(cursor1.getColumnIndex("cityid"));
					Cursor cursor2 = sqliteDB.query(TABLE_NAME.TABLE_AREA, new String[]{"area", "areaid"}, "father = ?", new String[]{cityid}, null, null, null);
					districtList = new ArrayList<>();
					while (cursor2.moveToNext()) {
						districtModel = new DistrictInfoModel();
						String area = cursor2.getString(cursor2.getColumnIndex("area"));
						districtModel.setName(area);
						districtList.add(districtModel);
					}
					cursor2.close();
					cityMode.setName(city);
					cityMode.setDistrictList(districtList);
					cityList.add(cityMode);
				}
				cursor1.close();
				provinceModel.setName(province);
				provinceModel.setCityList(cityList);
				provinceList.add(provinceModel);
			}
			cursor.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return provinceList;
	}
}
